import React, { useEffect, useRef, useState } from 'react';
import { InputNumber, Button, Card, Col, Divider, Form, Input, Modal, Row, Select, Table, Typography, Spin, DatePicker } from "antd";
import { ShareAltOutlined } from "@ant-design/icons";
import styles from './styles.module.less';
import { useNavigate } from 'react-router';
import moment from 'moment';
import TextArea from "antd/es/input/TextArea";
import { useTranslation } from 'react-i18next';

import { getMyBidding, biddingNowApi, biddingRejectApi } from '@src/services/biddingProject';
import { formatTimeDifference } from '@src/utils/dataHandlingFunc';
import dobleModalConfig from '@src/utils/dobleModalConfig';

const { Title, Paragraph, Text, Link } = Typography;


const AllMarket = () => {
    const { t } = useTranslation();
    const navigate = useNavigate();
    const biddingNowFormRef = useRef(null);

    const [requirementModalVisible, setRequirementModalVisible] = useState(false);
    const [biddingLoading, setBiddingLoading] = useState(false);
    const [biddingData, setBiddingData] = useState([]);
    const [biddingRowKey, setBiddingRowKey] = useState([]);
    const [biddingRowData, setBiddingRowData] = useState({});
    const [biddingNowLoading, setBiddingNowLoading] = useState(false);
    const [biddingNowSubmitLoading, setBiddingNowSubmitLoading] = useState(false);

    useEffect(() => {
        onLoad();
    }, [])

    const onLoad = async () => {
        setBiddingLoading(true);

        const res = await getMyBidding();

        if (!res) return;

        setBiddingLoading(false);
        setBiddingData(res);

        let newBiddingRowKey = [];
        setBiddingRowKey(old => {
            newBiddingRowKey = old;
            return old;
        });

        if ((!newBiddingRowKey[0]) && res.length) {
            const defaultSelectRowData = res?.filter(item => item.state === 10) || [];

            setBiddingRowKey(defaultSelectRowData.length ? [defaultSelectRowData?.[0]?.tender_id] : []);
            setBiddingRowData(defaultSelectRowData?.[0] || {});
        }
    }

    const onBiddingNowFinish = async (data) => {
        setBiddingNowSubmitLoading(true);
        const res = await biddingNowApi({
            tender_id: biddingRowData.tender_id,
            ...data,
            delivery_time: moment(data.delivery_time).format('YYYY-MM-DD HH:mm:ss')
        });

        setBiddingNowSubmitLoading(false);
        if (!res) return;
        setBiddingRowKey([]);
        setBiddingRowData({});
        onCancleBiddingModal();
        onLoad();
    }

    const onBiddingReject = async (id) => {
        const configFlag = await dobleModalConfig('您确定要拒绝投标吗？');
        if (!configFlag) return;

        setBiddingNowLoading(true);
        const res = await biddingRejectApi({
            tender_id: id
        });

        setBiddingNowLoading(false);
        if (!res) return;
        setBiddingRowKey([]);
        setBiddingRowData({});
        onLoad();
    }

    const onBiddingSelectChange = (rowData) => {
        setBiddingRowKey([rowData.tender_id]);
        setBiddingRowData(rowData);
    }

    const onCancleBiddingModal = () => {
        setRequirementModalVisible(false);
        biddingNowFormRef?.current?.resetFields();
    }


    // 等待投标
    const pendingColumns = [
        {
            title: t('Title'),
            dataIndex: 'title',
            key: 'title',
        },
        {
            title: t('Expiration time'),
            dataIndex: 'expiration_date',
            key: 'expiration_date',
            render: (_, record) => (
                <span>{formatTimeDifference(record.expiration_date)}</span>
            )
        },
        {
            title: t('State'),
            dataIndex: 'state',
            key: 'state',
            render: (_, record) => (
                <span>{t('Waiting for bidding')}</span>
            )
        },
    ];

    // 已收到投标
    const receivedColumns = [
        {
            title: t('Title'),
            dataIndex: 'title',
            key: 'title',
        },
        {
            title: t('Expiration time'),
            dataIndex: 'expiration_date',
            key: 'expiration_date',
            render: (_, record) => (
                <span>{formatTimeDifference(record.expiration_date)}</span>
            )
        },
        {
            title: t('State'),
            dataIndex: 'bid_count',
            key: 'bid_count',
            render: (_, record) => (
                <span>{t('Received')}+{record.bid_count}</span>
            )
        },
    ];

    // 已完成投标
    const finishedColumns = [
        {
            title: t('Title'),
            dataIndex: 'title',
            key: 'title',
        },
        {
            title: t('Expiration time'),
            dataIndex: 'expiration_date',
            key: 'expiration_date',
            render: (_, record) => (
                <span>{formatTimeDifference(record.expiration_date)}</span>
            )
        },
        {
            title: t('State'),
            dataIndex: 'state',
            key: 'state',
            render: (_, record) => (
                <span>{t('Completed')}</span>
            )
        },
    ];

    const disabledDate = (current) => {
        // 禁用过期时间
        if (current < moment().add(0, 'days')) {
            return true;
        }

        return false;
    };

    return (
        <div className={styles.my_market}>
            <Divider orientation="left">
                <Button type="primary" onClick={() => navigate('/market')} >{t('All items')}</Button>
            </Divider>
            <Spin spinning={biddingLoading}>
                <Row gutter={16}>
                    <Col span={12}>
                        <Divider orientation="left">{t('Opportunity')}</Divider>
                        {console.log(biddingData)}
                        <Table
                            dataSource={biddingData?.filter(item => item.state === 10 && (formatTimeDifference(item.expiration_date) !== 'Expired')) || []}
                            columns={pendingColumns}
                            pagination={{
                                pageSize: 5,
                                size: 'small'
                            }}
                            rowKey="tender_id"
                            rowSelection={{
                                selectedRowKeys: biddingRowKey,
                                // onChange: onBiddingSelectChange,
                                onSelect: onBiddingSelectChange,
                                hideSelectAll: true,
                                type: 'radio',
                            }}
                            onRow={record => {
                                return {
                                    onClick: () => {
                                        onBiddingSelectChange(record)
                                    }
                                }
                            }}
                        />
                        <Divider orientation="left">{t('Already bid')}</Divider>
                        <Table
                            dataSource={biddingData?.filter(item => item.state === 20)}
                            columns={receivedColumns}
                            pagination={{
                                pageSize: 5,
                                size: 'small'
                            }}
                            rowKey="tender_id"
                        />
                        <Divider orientation="left">{t('Completed bidding items')}</Divider>
                        <Table
                            dataSource={biddingData?.filter(item => item.state === 1)}
                            columns={finishedColumns}
                            pagination={{
                                pageSize: 5,
                                size: 'small'
                            }}
                            rowKey="tender_id"
                        />
                    </Col>
                    <Col span={12} style={{ backgroundColor: '#fff', borderRadius: '20px', padding: '20px' }}>
                        <Paragraph>
                            <pre>{t('Your company has been accepted to participate in this tender. Please reply to indicate whether your company can meet the requirements and intends to bid.')}</pre>
                        </Paragraph>
                        {
                            !!biddingRowData.tender_id && (
                                <div className={styles.invite_span}>
                                    <Spin spinning={biddingNowLoading}>
                                        <span>
                                            <Button
                                                type="primary"
                                                onClick={() => {
                                                    setRequirementModalVisible(true);
                                                }}
                                            >
                                                {t('Bid Now')}
                                            </Button>
                                        </span>
                                        <span style={{ margin: '0 10px' }}>
                                            <Button
                                                type="primary"
                                                danger
                                                onClick={() => {
                                                    onBiddingReject(biddingRowData.tender_id);
                                                }}
                                            >
                                                {t('Rejection of Bid')}
                                            </Button>
                                        </span>
                                    </Spin>
                                    <span><ShareAltOutlined style={{ fontSize: '28px', color: '#08c', marginLeft: '20px' }} /></span>
                                </div>
                            )
                        }

                        <div className={styles.title}>
                            {biddingRowData.title || ''}
                        </div>
                        <Divider orientation="left"></Divider>
                        <div>
                            <Row>
                                <Col span={12}>
                                    <p className={styles.little_desc}>{t('Source')}</p>
                                    <p className={styles.little_content}>{biddingRowData?.source?.city?.[sessionStorage.getItem('ai_lang')] || ''}</p>
                                </Col>
                                <Col span={12}>
                                    <p className={styles.little_desc}>{t('Destination')}</p>
                                    <p className={styles.little_content}>{biddingRowData?.destination?.city?.[sessionStorage.getItem('ai_lang')] || ''}</p>
                                </Col>
                            </Row>

                            <Row>
                                <Col span={6}>
                                    <p className={styles.little_desc}>{t('Cooperation period')}</p>
                                    <p className={styles.little_content}>{biddingRowData?.expiration_date ? formatTimeDifference(biddingRowData?.expiration_date) : ''}</p>
                                </Col>
                                <Col span={6}>
                                    <p className={styles.little_desc}>{t('Expected delivery time')}</p>
                                    <p className={styles.little_content}>{biddingRowData?.expiration_date ? moment(biddingRowData?.expiration_date).format('YYYY/MM/DD') : ''}</p>
                                </Col>
                                <Col span={6}>
                                    <p className={styles.little_desc}>{t('Bandwidth')}</p>
                                    <p className={styles.little_content}>{biddingRowData?.bandwidth ? `${biddingRowData?.bandwidth} M` : ''}</p>
                                </Col>
                                <Col span={6}>
                                    <p className={styles.little_desc}>{t('Access method')}</p>
                                    <p className={styles.little_content}>{biddingRowData?.business_name || ''}</p>
                                </Col>
                            </Row>
                            <Row>
                                <Col span={12}>
                                    <p className={styles.little_desc}>{t('Additional description')}</p>
                                    <p className={styles.little_content}>{biddingRowData?.description || ''}</p>
                                </Col>
                            </Row>
                        </div>

                        <div>
                            <Row>
                                <Col span={12}>
                                    <p className={styles.little_desc}>{t('Market')}</p>
                                </Col>
                            </Row>
                            <Row>
                                <Col span={12}>
                                    <Card style={{ width: 300 }}>
                                        <Row>
                                            {
                                                biddingRowData?.destination?.country?.national_flag && (
                                                    <img style={{ width: '80px' }} src={`/api${biddingRowData?.destination?.country?.national_flag}`} />
                                                )
                                            }
                                            <Col style={12}>
                                                <p className={styles.little_desc} style={{ marginLeft: '10px', marginTop: '-5px' }}>{biddingRowData?.destination?.city?.[sessionStorage.getItem('ai_lang')]}</p>
                                                <p className={styles.little_content} style={{ marginLeft: '10px' }}>{biddingRowData?.destination?.country?.[sessionStorage.getItem('ai_lang')]}</p>
                                            </Col>
                                        </Row>
                                    </Card>
                                </Col>
                                {/* <Col span={12}>
                                    <Card style={{ width: 300 }}>
                                        <Row>
                                            <Col style={12}><img style={{ width: '80px' }} src='/img/dibaiFlag.jpg' /></Col>
                                            <Col style={12}>
                                                <p className={styles.little_desc} style={{ marginLeft: '10px', marginTop: '-5px' }}>迪拜</p>
                                                <p className={styles.little_content} style={{ marginLeft: '10px' }}>中东</p>

                                            </Col>
                                        </Row>
                                    </Card>
                                </Col> */}
                            </Row>

                        </div>
                        {
                            (biddingRowData?.attachments?.length > 0) && (
                                <div>
                                    <p className={styles.little_desc}>{t('Enclosure')}</p>
                                    {
                                        biddingRowData?.attachments?.map((item, index) => (
                                            <p key={index}>
                                                <a
                                                    className={styles.little_content}
                                                    href={`${process.env.APISERVER}${item}`}
                                                    // download={item?.split('/')?.slice(-1)[0]}
                                                    download={t('Download')}
                                                    style={{ color: 'blue' }}
                                                    target="_blank"
                                                >
                                                    {item?.split('/')?.slice(-1)[0]}
                                                </a>
                                            </p>
                                        ))
                                    }
                                </div>
                            )
                        }

                    </Col>
                </Row>
            </Spin>
            <Modal
                open={requirementModalVisible}
                footer={null}
                onCancel={onCancleBiddingModal}
                style={{ minWidth: 650 }}
            >
                <div className={styles.requirement_modal_box}>
                    <div className={styles.title}>{t('Participate in bidding')}</div>
                    <div className={styles.form_box}>
                        <Form layout="vertical" onFinish={onBiddingNowFinish} ref={biddingNowFormRef}>
                            <Form.Item label={t('Estimated costs')} name="budget" required>
                                <InputNumber name="budget" />
                            </Form.Item>
                            <Form.Item label={t('Delivery time')} name="delivery_time" required>
                                <DatePicker
                                    name="delivery_time"
                                    showTime
                                    style={{ width: '100%' }}
                                    disabledDate={disabledDate}
                                />
                            </Form.Item>
                            <Form.Item label={t('Description of the program')} name="description" required>
                                <TextArea name="description" />
                            </Form.Item>
                            <div className={styles.footer_box}>
                                <Button type='ghost' onClick={onCancleBiddingModal}>{t('Cancel')}</Button>
                                <Button type='primary' htmlType='submit' loading={biddingNowSubmitLoading} >{t('Submit')}</Button>
                            </div>
                        </Form>
                    </div>
                </div>
            </Modal>

        </div>
    );
};

export default AllMarket;
